package com.example.repositories;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import com.example.dto.User;



public class UserRepository extends SQLiteOpenHelper  {

    private final String TableName = "user";

    public UserRepository(@Nullable Context context) {
        super(context, "testDB", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS "+TableName+" (\n" +
                "  \"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
                "  \"account\" text NOT NULL,\n" +
                "  \"password\" TEXT NOT NULL\n" +
                ");");


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public long insert(User user){

        ContentValues contentValues = new ContentValues();
        contentValues.put("account",user.getAccount());
        contentValues.put("password",user.getPassword());
        return getWritableDatabase().insert(TableName,null,contentValues);
    }

    public long update(User user){
        ContentValues contentValues = new ContentValues();
        contentValues.put("password",user.getPassword());
        return getWritableDatabase().update(TableName,contentValues," id = ?",new String[]{String.valueOf(user.getId())});
    }

    public long delete(String account){
        return getWritableDatabase().delete(TableName," account = ?",new String[]{account});
    }

    public User findByAccount(String account){
        try(Cursor cursor = getReadableDatabase().query(TableName, new String[]{ "id","account", "password"}, " account = ?",
                new String[]{account}, null, null, null
        )) {
            return buildUser(cursor);

        }
    }

    private static @Nullable User buildUser(Cursor cursor) {
        if (cursor.moveToNext()) {
            User user = new User();
            user.setId(cursor.getInt(0));
            user.setAccount(cursor.getString(1));
            user.setPassword(cursor.getString(2));
            return user;
        }
        return null;
    }

    public User findLatest() {
        try(Cursor cursor = getReadableDatabase().query(TableName, new String[]{ "id","account", "password"}, null,
                null, null, null, "id desc","1"
        )) {
            return buildUser(cursor);
        }
    }
}
